import axios from 'axios'
import { Message } from 'element-ui'
// create an axios instance
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
    (config) => {
        return config
    },
    (error) => {
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    (res) => {
        // 统一错误处理,密码账号写错时,状态码依旧是200,返回的数据中以res.data.success确定是否用户正常登录
        if (res.data.success) {
            return res
        } else {
            // 错误信息提示
            Message.error(res.data.message)
                // 抛出错误,阻止pormise后续代码的执行,防止Vuex中的user.js模块中,store.commit('setToken', res.data.data)中的res.data为undefined
            return Promise.reject(res.data.message)
        }
    },
    (error) => {
        return Promise.reject(error)
    }
)

export default service